﻿using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using Maticsoft.DBUtility;//Please add references
namespace lcs.DAL
{
	/// <summary>
	/// 数据访问类:inventory
	/// </summary>
	public partial class inventory
	{
		public inventory()
		{}
        public bool Updatenums(int mid, int spid, decimal nums)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update inventory set ");
            strSql.Append("nums=nums-@nums ");
            strSql.Append(" where mid=@mid and spid=@spid ");
            SqlParameter[] parameters = {	
				    new SqlParameter("@nums", SqlDbType.Decimal,9),
					new SqlParameter("@mid", SqlDbType.Int,4),					
					new SqlParameter("@spid", SqlDbType.Int,4)};
            parameters[0].Value = nums;
            parameters[1].Value = mid;
            parameters[2].Value = spid;
            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 通过mid spid 获取库存量
        /// </summary>
        /// <param name="mid"></param>
        /// <param name="spid"></param>
        /// <returns></returns>
        public decimal Getnums(int mid, int spid)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select nums from inventory where mid=@mid and spid=@spid ");
            SqlParameter[] parameters = {					
					new SqlParameter("@mid", SqlDbType.Int,4),					
					new SqlParameter("@spid", SqlDbType.Int,4)};
            parameters[0].Value = mid;
            parameters[1].Value = spid;
            object nums = DbHelperSQL.GetSingle(strSql.ToString(), parameters);
            decimal num = 0;
            if (nums != null)
            {
                decimal.TryParse(nums.ToString(), out num);
                return num;
            }
            else
            {
                num = decimal.Parse(nums.ToString());
                return num;
            }
        }
        /// <summary>
        /// 获取项目物料累计库存量
        /// </summary>
        public DataSet GetSumNumsProjectInventory(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select sum(nums) as nums,mid,material,projectName,proid,unit ");
            strSql.Append("from VprojectInventroyNums  ");

            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }

            strSql.Append(" group by mid,material,projectName,proid,unit ");

        

            return DbHelperSQL.Query(strSql.ToString());
        }
        /// <summary>
        /// 获取项目物料库存量
        /// </summary>
        public DataSet GetListMaterialInventoryProject(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from VmaterialInventoryProject ");

            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }

            return DbHelperSQL.Query(strSql.ToString());
        }
 
        /// <summary>
        /// 获取项目物料库存入库数量
        /// </summary>
        public DataSet GetListMaterialInventoryInstore(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from VmaterialInventory ");

            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
           
            return DbHelperSQL.Query(strSql.ToString());
        }
 
        public DataSet Getmatralbyspid(int spid)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select mid,material ");
            strSql.Append(" FROM Vinventory where 1=1 and mid is not null and spid="+spid);            
            return DbHelperSQL.Query(strSql.ToString());
        }
        public bool Updatenums(int inid,decimal newnum)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update inventory set ");
            strSql.Append("nums=@nums ");
            strSql.Append(" where inid=@inid");
            SqlParameter[] parameters = {					
					new SqlParameter("@nums", SqlDbType.Decimal,9),					
					new SqlParameter("@inid", SqlDbType.Int,4)};
            parameters[0].Value = newnum;
            parameters[1].Value = inid;

            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public bool Updateadjust(int outid,int inid)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update inventory set ");            
            strSql.Append("spid=@spid ");           
            strSql.Append(" where spid=@inid");
            SqlParameter[] parameters = {					
					new SqlParameter("@spid", SqlDbType.Int,4),					
					new SqlParameter("@inid", SqlDbType.Int,4)};
            parameters[0].Value = inid;
            parameters[1].Value =outid;           

            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public bool Updateadjustinid(int spid, int inid,string mark)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update inventory set ");
            strSql.Append("spid=@spid,imark=@imark ");
            strSql.Append(" where inid=@inid");
            SqlParameter[] parameters = {
                    new SqlParameter("@spid", SqlDbType.Int,4),
                     new SqlParameter("@imark", SqlDbType.NVarChar,200),
                    new SqlParameter("@inid", SqlDbType.Int,4)};
            parameters[0].Value = spid;
            parameters[1].Value = mark;
            parameters[2].Value = inid;

            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public bool Updateadjustbymid(int outid, int inid,string mid,int status)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update inventory set ");
            strSql.Append("spid=@spid ");
            strSql.Append(" where spid=@inid and mid in ("+mid+")");
            SqlParameter[] parameters = {					
					new SqlParameter("@spid", SqlDbType.Int,4),					
					new SqlParameter("@inid", SqlDbType.Int,4)};
            parameters[0].Value = inid;
            parameters[1].Value = outid;

            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                //更新仓位状态
                spaceinfo sp = new spaceinfo();
                sp.UpdateStatus(inid, status);
                return true;
            }
            else
            {
                return false;
            }
        }
        public DataSet Getinventory(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * ");
            strSql.Append(" FROM Vinventory where 1=1 and mid is not null ");
            if (strWhere.Trim() != "")
            {
                strSql.Append( strWhere);
            }
            return DbHelperSQL.Query(strSql.ToString());
        }
        /// <summary>
        /// 获取记录总数
        /// </summary>
        public int GetinventoryRecordCount(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) FROM Vinventory where 1=1 and mid is not null ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(strWhere);
            }
            object obj = DbHelperSQL.GetSingle(strSql.ToString());
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GetinventoryListByPage(string strWhere, string orderby, int startIndex, int endIndex)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT * FROM ( ");
            strSql.Append(" SELECT ROW_NUMBER() OVER (");
            if (!string.IsNullOrEmpty(orderby.Trim()))
            {
                strSql.Append("order by T." + orderby);
            }
            else
            {
                strSql.Append("order by T.inid desc");
            }
            strSql.Append(")AS Row, T.*  from (select * from Vinventory where mid is not null");
            if (!string.IsNullOrEmpty(strWhere.Trim()))
            {
                strSql.Append(strWhere);
            }
            strSql.Append(") T  ) TT");
            strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
            return DbHelperSQL.Query(strSql.ToString());
        }
        /// <summary>
        /// 获取记录总数
        /// </summary>
        public int GettakestoreRecordCount(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) FROM Vinventory where 1=1 and mid is not null ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(strWhere);
            }
            object obj = DbHelperSQL.GetSingle(strSql.ToString());
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GettakestoreListByPage(string strWhere, string orderby, int startIndex, int endIndex)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT * FROM ( ");
            strSql.Append(" SELECT ROW_NUMBER() OVER (");
            if (!string.IsNullOrEmpty(orderby.Trim()))
            {
                strSql.Append("order by T." + orderby);
            }
            else
            {
                strSql.Append("order by T.inid desc");
            }
            strSql.Append(")AS Row, T.*  from (select * from Vinventory where 1=1 and mid is not null) T ");
            if (!string.IsNullOrEmpty(strWhere.Trim()))
            {
                strSql.Append(" WHERE 1=1" + strWhere);
            }
            strSql.Append(" ) TT");
            strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
            return DbHelperSQL.Query(strSql.ToString());
        }
        public DataSet Gettakestore(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select inid,[material],spname,unit, sptname,sname,status,nums,proid,usework,projectname,projecttype,mid,supplier,purchaseid,real_count ");
            strSql.Append(" FROM Vinventory where 1=1 and mid is not null ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(strWhere);
            }
            return DbHelperSQL.Query(strSql.ToString());
        }
        public int Addin(int mid,int spid,float nums)
        {            
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into inventory(");
            strSql.Append("mid,spid,nums)");
            strSql.Append(" values (");
            strSql.Append("@mid,@spid,@nums)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
					new SqlParameter("@mid", SqlDbType.Int,4),
					new SqlParameter("@spid", SqlDbType.Int,4),
					new SqlParameter("@nums", SqlDbType.Decimal,9)};
            parameters[0].Value = mid;
            parameters[1].Value =spid;
            parameters[2].Value = nums;

            object obj = DbHelperSQL.GetSingle(strSql.ToString(), parameters);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }

        public int Addin(int mid, int spid, decimal nums)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into inventory(");
            strSql.Append("mid,spid,nums)");
            strSql.Append(" values (");
            strSql.Append("@mid,@spid,@nums)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
					new SqlParameter("@mid", SqlDbType.Int,4),
					new SqlParameter("@spid", SqlDbType.Int,4),
					new SqlParameter("@nums", SqlDbType.Decimal,9)};
            parameters[0].Value = mid;
            parameters[1].Value = spid;
            parameters[2].Value = nums;

            object obj = DbHelperSQL.GetSingle(strSql.ToString(), parameters);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
		#region  BasicMethod

		/// <summary>
		/// 得到最大ID
		/// </summary>
		public int GetMaxId()
		{
		return DbHelperSQL.GetMaxID("inid", "inventory"); 
		}

		/// <summary>
		/// 是否存在该记录
		/// </summary>
		public bool Exists(int inid)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) from inventory");
			strSql.Append(" where spid=@spid");
			SqlParameter[] parameters = {
					new SqlParameter("@spid", SqlDbType.Int,4)
			};
			parameters[0].Value = inid;

			return DbHelperSQL.Exists(strSql.ToString(),parameters);
		}


		/// <summary>
		/// 增加一条数据
		/// </summary>
		public int Add(lcs.Model.inventory model)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("insert into inventory(");
			strSql.Append("mid,spid,nums)");
			strSql.Append(" values (");
			strSql.Append("@mid,@spid,@nums)");
			strSql.Append(";select @@IDENTITY");
			SqlParameter[] parameters = {
					new SqlParameter("@mid", SqlDbType.Int,4),
					new SqlParameter("@spid", SqlDbType.Int,4),
					new SqlParameter("@nums", SqlDbType.Decimal,9)};
			parameters[0].Value = model.mid;
			parameters[1].Value = model.spid;
			parameters[2].Value = model.nums;

			object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters);
			if (obj == null)
			{
				return 0;
			}
			else
			{
				return Convert.ToInt32(obj);
			}
		}
		/// <summary>
		/// 更新一条数据
		/// </summary>
		public bool Update(lcs.Model.inventory model)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("update inventory set ");
			strSql.Append("mid=@mid,");
			strSql.Append("spid=@spid,");
			strSql.Append("nums=@nums");
			strSql.Append(" where inid=@inid");
			SqlParameter[] parameters = {
					new SqlParameter("@mid", SqlDbType.Int,4),
					new SqlParameter("@spid", SqlDbType.Int,4),
					new SqlParameter("@nums", SqlDbType.Decimal,9),
					new SqlParameter("@inid", SqlDbType.Int,4)};
			parameters[0].Value = model.mid;
			parameters[1].Value = model.spid;
			parameters[2].Value = model.nums;
			parameters[3].Value = model.inid;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// 删除一条数据
		/// </summary>
		public bool Delete(int inid)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from inventory ");
			strSql.Append(" where inid=@inid");
			SqlParameter[] parameters = {
					new SqlParameter("@inid", SqlDbType.Int,4)
			};
			parameters[0].Value = inid;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		/// <summary>
		/// 批量删除数据
		/// </summary>
		public bool DeleteList(string inidlist )
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from inventory ");
			strSql.Append(" where inid in ("+inidlist + ")  ");
			int rows=DbHelperSQL.ExecuteSql(strSql.ToString());
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}


		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public lcs.Model.inventory GetModel(int inid)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select  top 1 inid,mid,spid,nums from inventory ");
			strSql.Append(" where inid=@inid");
			SqlParameter[] parameters = {
					new SqlParameter("@inid", SqlDbType.Int,4)
			};
			parameters[0].Value = inid;

			lcs.Model.inventory model=new lcs.Model.inventory();
			DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters);
			if(ds.Tables[0].Rows.Count>0)
			{
				return DataRowToModel(ds.Tables[0].Rows[0]);
			}
			else
			{
				return null;
			}
		}


		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public lcs.Model.inventory DataRowToModel(DataRow row)
		{
			lcs.Model.inventory model=new lcs.Model.inventory();
			if (row != null)
			{
				if(row["inid"]!=null && row["inid"].ToString()!="")
				{
					model.inid=int.Parse(row["inid"].ToString());
				}
				if(row["mid"]!=null && row["mid"].ToString()!="")
				{
					model.mid=int.Parse(row["mid"].ToString());
				}
				if(row["spid"]!=null && row["spid"].ToString()!="")
				{
					model.spid=int.Parse(row["spid"].ToString());
				}
				if(row["nums"]!=null && row["nums"].ToString()!="")
				{
					model.nums=decimal.Parse(row["nums"].ToString());
				}
			}
			return model;
		}

		/// <summary>
		/// 获得数据列表
		/// </summary>
		public DataSet GetList(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select inid,mid,spid,nums ");
			strSql.Append(" FROM inventory ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获得前几行数据
		/// </summary>
		public DataSet GetList(int Top,string strWhere,string filedOrder)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select ");
			if(Top>0)
			{
				strSql.Append(" top "+Top.ToString());
			}
			strSql.Append(" inid,mid,spid,nums ");
			strSql.Append(" FROM inventory ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			strSql.Append(" order by " + filedOrder);
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获取记录总数
		/// </summary>
		public int GetRecordCount(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) FROM inventory ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			object obj = DbHelperSQL.GetSingle(strSql.ToString());
			if (obj == null)
			{
				return 0;
			}
			else
			{
				return Convert.ToInt32(obj);
			}
		}
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("SELECT * FROM ( ");
			strSql.Append(" SELECT ROW_NUMBER() OVER (");
			if (!string.IsNullOrEmpty(orderby.Trim()))
			{
				strSql.Append("order by T." + orderby );
			}
			else
			{
				strSql.Append("order by T.inid desc");
			}
			strSql.Append(")AS Row, T.*  from inventory T ");
			if (!string.IsNullOrEmpty(strWhere.Trim()))
			{
				strSql.Append(" WHERE " + strWhere);
			}
			strSql.Append(" ) TT");
			strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
			return DbHelperSQL.Query(strSql.ToString());
		}

		/*
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetList(int PageSize,int PageIndex,string strWhere)
		{
			SqlParameter[] parameters = {
					new SqlParameter("@tblName", SqlDbType.VarChar, 255),
					new SqlParameter("@fldName", SqlDbType.VarChar, 255),
					new SqlParameter("@PageSize", SqlDbType.Int),
					new SqlParameter("@PageIndex", SqlDbType.Int),
					new SqlParameter("@IsReCount", SqlDbType.Bit),
					new SqlParameter("@OrderType", SqlDbType.Bit),
					new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
					};
			parameters[0].Value = "inventory";
			parameters[1].Value = "inid";
			parameters[2].Value = PageSize;
			parameters[3].Value = PageIndex;
			parameters[4].Value = 0;
			parameters[5].Value = 0;
			parameters[6].Value = strWhere;	
			return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
		}*/

		#endregion  BasicMethod
		#region  ExtensionMethod
        /// <summary>
        /// 获取应急出库列表（剩余数量 = 库存量-已申请出库计划未出库量）
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public DataSet GetMaterialInventoryOutStorageList(string where)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(" select *, ");
            strSql.Append(" (case when deal_status='已出库' or out_storage_count is null then nums ");
            strSql.Append(" else nums -out_storage_count end) as realCount ");
            strSql.Append(" from VmaterialInventoryOutStoreList ");

            if (where.Trim() != "")
            {
                strSql.Append(" where " + where);
            }

            return DbHelperSQL.Query(strSql.ToString());
        }

        /// <summary>
        /// 获取库存,real_count=库存数量（当前的库存量）-已申请的出库数量（不包括已出库的数量(deal_status<>'已出库')），当real_counts值为Null时，代表此条物料未申请出库，应以库存(库存表inventory表的nums)数量计算（ventroyNums）
        /// real_count在语句中已作出了判断，当real_counts为null时赋值real_count为ventroyNums，否则就是real_counts值
        /// 所以real_count的值就是剩余数量（库存量）
        /// </summary>
        public DataSet GetMaterialVentoryInfo(string proid,string where)
        {
            //StringBuilder strSql = new StringBuilder();
            //strSql.Append("select projectname,material,sum(ventoryNums) as ventoryNums,unit,supplier,proid,usework,mid from VmaterialVentoryInfo ");
            //if (strWhere.Trim() != "")
            //{
            //    strSql.Append(" where " + strWhere);
            //}
            //strSql.Append(" group by material,projectname,supplier,unit,proid,usework,mid ");
            //return DbHelperSQL.Query(strSql.ToString());

            StringBuilder strSql = new StringBuilder();
            strSql.Append(" select * from ( ");
            strSql.Append(" select (case when real_counts is null then ventoryNums   else real_counts end) as real_count ,* from ( ");
            strSql.Append(" select (ventoryNums-(select out_count from(select distinct material_id,sum(out_storage_count) as out_count from (select  material_id,out_storage_count,check_status,deal_status from out_storageList  where deal_status='未处理' ) AS X  ");
            strSql.Append(" where material_id in (select mid from materialinfo where proid ='" + proid + "') ");
            strSql.Append(" group by material_id) AS Y where mid = material_id ) ) as real_counts,* from ( ");
            strSql.Append(" select projectname,material,sum(ventoryNums) as ventoryNums,unit,supplier,proid,usework,mid,sname,spname,imark from VmaterialInstore ");
            strSql.Append(" where  proid='" + proid + "'   ");
            strSql.Append(" group by material,projectname,supplier,unit,proid,usework,mid,sname,spname,imark ) AS Z ) AS C");
            strSql.Append(" ) AS D where real_count > 0 ");

            if (!string.IsNullOrEmpty(where))
            {
                strSql.Append(where );
            }
           
            return DbHelperSQL.Query(strSql.ToString());
        }


		#endregion  ExtensionMethod
	}
}

